package com.example.demo.service;

import com.example.demo.model.Book;
import com.example.demo.repository.BookRepository;
import jakarta.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.List;
import java.util.Optional;

@Service
public class BookService {

    @Autowired
    private BookRepository bookRepository;
    
    public List<Book> getAllBooks() {
        return bookRepository.findAll();
    }

    public Optional<Book> getBookById(Long id) {
        return bookRepository.findById(id);
    }

    public Book addBook(Book book) {
        return bookRepository.save(book);
    }

    public Book updateBook(Long id, Book bookUpdate) {
        return bookRepository.findById(id).map(
                book -> {
                    book.setTitle(bookUpdate.getTitle());
                    book.setAuthor(bookUpdate.getAuthor());
                    book.setContent(bookUpdate.getAuthor());
                    return bookRepository.save(book);
                }
        ).orElseThrow(() -> new RuntimeException("Book not found with id: " + id));
    }

    public void deleteBook(Long id) {
        bookRepository.deleteById(id);
    }

    @Transactional
    public Book AddOneBook(Book book) {
        Book book1 = bookRepository.save(book);
        if (book.getTitle().equals("same title")) {
            throw new RuntimeException("Book already exists with title: " + book.getTitle());
        }
        return book1;
    }


}
